package org.ronghao.androidwifiplatfrom;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.ronghao.androidwifiplatfrom.entity.Game;
import org.ronghao.androidwifiplatfrom.entity.MessageQueue;
import org.ronghao.androidwifiplatfrom.entity.User;
import org.ronghao.androidwifiplatfrom.entity.WifiAPInfo;
import org.ronghao.androidwifiplatfrom.socket.SocketClient;
import org.ronghao.androidwifiplatfrom.utils.Contants;
import org.ronghao.androidwifiplatfrom.utils.MessageUtils;
import org.ronghao.androidwifiplatfrom.utils.Wifi;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;

public class Facade {
	private Wifi mWifi;
	private static int i = 0;// 计数

	public Facade(Context context) {
		mWifi = Wifi.getInstance(context);
	}

	/**
	 * 退出
	 * 
	 * @author ronghao
	 * @data 2012-11-28 上午9:31:35
	 */
	public void exit() {
		mWifi.exit();
	}

	/**
	 * 重置
	 * 
	 * @author ronghao
	 * @data 2012-11-28 上午9:31:44
	 */
	public void reset() {
		mWifi.reset();
	}

	/**
	 * 创建一个连接主机的socket
	 * 
	 * @author ronghao
	 * @data 2012-11-22 上午11:18:23
	 * @return
	 */
	public SocketClient createSocketClient(int type, String action,
			String msgData) {
		// return new SocketClient(mWifi.getDHCPIP(), new MessageQueue(i,
		// mWifi.getIpAddress(), mWifi.getLocalUser().getName(), type,
		// action, msgData).toString());
		return new SocketClient(mWifi.getDHCPIP(),
				MessageUtils.setData(new MessageQueue(i, mWifi.getIpAddress(),
						mWifi.getLocalUser().getName(), type, action, msgData)));
	}

	/**
	 * 创建游戏
	 * 
	 * @author ronghao
	 * @data 2012-11-20 下午2:54:32
	 * @param game
	 * @return
	 */
	public Game createGame(Game game) {
		closeWifi();
		closeAP();
		// UUID uuid = UUID.randomUUID();
		int type = WifiConfiguration.KeyMgmt.NONE;
		// TODO:UUID
		// String id = uuid.toString() + "-" + game.getGameName() + "-"
		// + game.getGameID() + "-" + game.getGameTotleNum();
		String id = game.getGameName() + "-" + game.getGameID() + "-"
				+ game.getGameTotleNum();
		type = game.getGamePassword().equals("") ? WifiConfiguration.KeyMgmt.NONE
				: WifiConfiguration.KeyMgmt.WPA_PSK;
		WifiAPInfo wifiAPInfo = new WifiAPInfo(id, game.getGamePassword(), type);
		int result = mWifi.startWifiAP(wifiAPInfo);
		game.setId(result);
		return game;
	}

	/**
	 * 开启wifi
	 * 
	 * @author ronghao
	 * @data 2012-11-26 下午7:12:06
	 */
	public void startWifi() {
		closeAP();
		mWifi.openWifi();
	}

	/**
	 * AP状态
	 * 
	 * @author ronghao
	 * @data 2012-11-26 下午4:14:22
	 * @return
	 */
	public Boolean getAPState() {
		return mWifi.getAPState();
	}

	/**
	 * wifi状态
	 * 
	 * @author ronghao
	 * @data 2012-11-27 下午6:19:15
	 * @return
	 */
	public boolean getWifiState() {
		return mWifi.checkState();
	}

	/**
	 * 关闭AP
	 * 
	 * @author ronghao
	 * @data 2012-11-30 下午2:44:44
	 */
	public void closeAP() {
		mWifi.closeWifiAP();
	}

	/**
	 * 关闭wifi
	 * 
	 * @author ronghao
	 * @data 2012-11-30 下午2:44:05
	 */
	public void closeWifi() {
		if (mWifi.getWifiState()) {
			mWifi.closeWifi();
		}
	}

	/**
	 * 获得所有游戏
	 * 
	 * @author ronghao
	 * @data 2012-11-23 下午6:25:02
	 * @return
	 */
	public List<Game> getGames() {
		mWifi.startScan();
		List<ScanResult> scanResults = mWifi.getWifiList();
		List<Game> games = new ArrayList<Game>();
		String[] stringBuffer;
		Game game = null;
		for (ScanResult scanResult : scanResults) {
			game = new Game();
			stringBuffer = scanResult.SSID.split("-");
			game.setGameName(stringBuffer[0]);
			game.setGameID(Integer.valueOf(stringBuffer[1]));
			game.setGameTotleNum(Integer.valueOf(stringBuffer[2]));
			games.add(game);
		}
		return games;
	}

	/**
	 * 添加一个用户
	 * 
	 * @author ronghao
	 * @data 2012-11-21 下午2:37:11
	 * @param user
	 */
	public void addUser(User user) {
		mWifi.addUser(user);
	}

	/**
	 * 删除一个user
	 * 
	 * @author ronghao
	 * @data 2012-11-29 下午7:29:14
	 * @param user
	 */
	public void deleteUser(User user) {
		mWifi.deleteUser(user);
	}

	/**
	 * 广播所有用户信息
	 * 
	 * @author ronghao
	 * @data 2012-11-21 下午2:37:11
	 * @param user
	 */
	public void updateUser(List<User> users) {
		mWifi.setmUsers(users);
	}

	/**
	 * 获得所有用户
	 * 
	 * @author ronghao
	 * @data 2012-11-21 下午2:37:26
	 * @return
	 */
	public List<User> getUsers() {
		return mWifi.getUsers();
	}

	/**
	 * 获得本机User
	 * 
	 * @author ronghao
	 * @data 2012-11-22 下午12:23:31
	 * @return
	 */
	public User getLocalUser() {
		return mWifi.getLocalUser();
	}

	/**
	 * 加入游戏
	 * 
	 * @author ronghao
	 * @data 2012-11-26 下午3:29:59
	 * @param index
	 * @return
	 */
	public int login(int index) {
		int i = 0;
		int result = 0;
		do {
			try {
				result = mWifi.connetionConfiguration(index);
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			i++;
		} while (result != 1 && i < 8);
		return result;
	}

	/**
	 * 加入游戏后更新IP
	 * 
	 * @author ronghao
	 * @data 2012-11-26 下午4:53:47
	 */
	public void updatarIp() {
		mWifi.updateIP();
	}

	/**
	 * 通知所有已知用户有人发送了信息
	 * 
	 * @author ronghao
	 * @data 2012-11-21 下午7:29:52
	 * @param msg
	 */
	public void notifyAllClients(String msg) {
		// TODO:如果有部分客户端接收不成功
		// TODO:delete
		// MessageQueue messageQueue = MessageQueue.createMessageQueue(msg);

		MessageQueue messageQueue = null;
		MessageUtils.getData(messageQueue, msg);

		notifyAllClients_LoginSpecialCase(messageQueue);

		messageQueue.setType(Contants.MSG_BROADCAST);

		// TODO:delete
		// String message = messageQueue.messageQueuetoString();
		String message = MessageUtils.setData(messageQueue);
		for (User user : getUsers()) {
			new SocketClient(user.getIp(), message).start();
		}
	}

	/**
	 * 登录特例
	 * 
	 * @author ronghao
	 * @data 2012-11-27 下午2:14:08
	 * @param messageQueue
	 */
	private void notifyAllClients_LoginSpecialCase(MessageQueue messageQueue) {
		// 如果是登录
		if (messageQueue.getAction().equals(Contants.MSG_ACTION_LOGIN)) {
			JSONArray jsonArray = new JSONArray();
			List<User> users = getUsers();
			for (User user : users) {
				jsonArray.put(MessageUtils.setData(user));
			}
			messageQueue.setMsgData(jsonArray.toString());
		}
	}

	/**
	 * 处理消息数据
	 * 
	 * @author ronghao
	 * @data 2012-11-21 下午7:44:33
	 * @param messageQueue
	 */
	public void handleMsg(MessageQueue messageQueue) {
		String action = messageQueue.getAction();
		int type = messageQueue.getType();
		if (type == Contants.MSG_UPDATE) {
			if (action.equals(Contants.MSG_ACTION_LOGIN)) {
				addUser((User) MessageUtils.getData(User.class,
						messageQueue.getMsgData()));
			} else if (action.equals(Contants.MSG_ACTION_LOGOUT)) {
				deleteUser((User) MessageUtils.getData(User.class,
						messageQueue.getMsgData()));
			}

			notifyAllClients(MessageUtils.setData(messageQueue));
		} else if (type == Contants.MSG_BROADCAST) {
			if (action.equals(Contants.MSG_ACTION_LOGIN)
					|| action.equals(Contants.MSG_ACTION_LOGOUT)) {
				List<User> users = (List<User>) MessageUtils.getJSONArray(
						User.class, messageQueue.getMsgData());
				updateUser(users);
			}
		}

	}
}
